package cn.iocoder.an.module.mold.controller.admin.upkeeptobe;

import cn.iocoder.an.framework.common.exception.ServiceException;

import cn.iocoder.an.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.an.module.business.dal.dataobject.warningconfig.WarningConfigDO;
import cn.iocoder.an.module.business.dal.mysql.warningconfig.WarningConfigMapper;
import cn.iocoder.an.module.mold.controller.admin.repairaccount.vo.RepairAccountAuditVO;
import cn.iocoder.an.module.mold.dal.dataobject.account.AccountDO;
import cn.iocoder.an.module.mold.service.account.AccountService;
import cn.iocoder.an.module.mold.service.upkeeptask.UpkeepTaskService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fhs.core.trans.anno.TransMethodResult;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.io.IOException;

import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.CommonResult;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import static cn.iocoder.an.framework.common.pojo.CommonResult.success;

import cn.iocoder.an.framework.excel.core.util.ExcelUtils;

import cn.iocoder.an.framework.apilog.core.annotation.ApiAccessLog;

import static cn.iocoder.an.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.an.module.mold.controller.admin.upkeeptobe.vo.*;
import cn.iocoder.an.module.mold.dal.dataobject.upkeeptobe.UpkeepTobeDO;
import cn.iocoder.an.module.mold.service.upkeeptobe.UpkeepTobeService;

@Tag(name = "管理后台 - 待保养模具")
@RestController
@RequestMapping("/mold/upkeep-tobe")
@Validated
public class UpkeepTobeController {

    @Resource
    private UpkeepTobeService upkeepTobeService;

    @Resource
    private UpkeepTaskService upkeepTaskService;

    @Resource
    private AccountService accountService;

    @Resource
    private WarningConfigMapper warningConfigMapper;

    @PostMapping("/create")
    @Operation(summary = "创建待保养模具")
    @PreAuthorize("@ss.hasPermission('mold:upkeep-tobe:create')")
    public CommonResult<Long> createUpkeepTobe(@Valid @RequestBody UpkeepTobeSaveReqVO createReqVO) {
        return success(upkeepTobeService.createUpkeepTobe(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新待保养模具")
    @PreAuthorize("@ss.hasPermission('mold:upkeep-tobe:update')")
    public CommonResult<Boolean> updateUpkeepTobe(@Valid @RequestBody UpkeepTobeSaveReqVO updateReqVO) {
        upkeepTobeService.updateUpkeepTobe(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除待保养模具")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mold:upkeep-tobe:delete')")
    public CommonResult<Boolean> deleteUpkeepTobe(@RequestParam("id") Long id) {
        upkeepTobeService.deleteUpkeepTobe(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除待保养模具")
    @PreAuthorize("@ss.hasPermission('mold:upkeep-tobe:delete')")
    public CommonResult<Boolean> deleteUpkeepTobeList(@RequestParam("ids") List<Long> ids) {
        upkeepTobeService.deleteUpkeepTobeListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得待保养模具")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mold:upkeep-tobe:query')")
    public CommonResult<UpkeepTobeRespVO> getUpkeepTobe(@RequestParam("id") Long id) {
        UpkeepTobeDO upkeepTobe = upkeepTobeService.getUpkeepTobe(id);
        return success(BeanUtils.toBean(upkeepTobe, UpkeepTobeRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得待保养模具分页")
    @PreAuthorize("@ss.hasPermission('mold:upkeep-tobe:query')")
    @TransMethodResult
    public CommonResult<PageResult<UpkeepTobeRespVO>> getUpkeepTobePage(@Valid UpkeepTobePageReqVO pageReqVO) {
        PageResult<UpkeepTobeDO> pageResult = upkeepTobeService.getUpkeepTobePage(pageReqVO);
        //1.先获取预警配置项 按照预警天数从大到小排序
        LambdaQueryWrapperX<WarningConfigDO> configWrapper = new LambdaQueryWrapperX<>();
        configWrapper.eq(WarningConfigDO::getWarningType, 4);
        configWrapper.orderByDesc(WarningConfigDO::getWarningDays);
        List<WarningConfigDO> configList = warningConfigMapper.selectList(configWrapper);
        if (CollectionUtils.isEmpty(configList)) {

        }
        if (pageResult.getList().size() > 0) {
            //循环pageResult.getList() 循环设置color字段
            pageResult.getList().forEach(upkeepTobeDO -> {
                //计算剩余日期
                AccountDO account = accountService.getAccount(upkeepTobeDO.getAccountId());
                //下次保养日期减去当前日期 得到剩余日期
                if (account.getNextUpkeepTime() !=null){
                    long between = ChronoUnit.DAYS.between(LocalDateTime.now(), account.getNextUpkeepTime());
                    //设置剩余天数
                    upkeepTobeDO.setRemaining((int) between);
                    //根据预警规则设置对应的背景颜色
                    for (WarningConfigDO config : configList) {
                        Integer warningDays = config.getWarningDays();
                        if (between <= warningDays) {
                            upkeepTobeDO.setColor(config.getWarningColor());

                        }
                    }
                }
            });
        }
        return success(BeanUtils.toBean(pageResult, UpkeepTobeRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出待保养模具 Excel")
    @PreAuthorize("@ss.hasPermission('mold:upkeep-tobe:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportUpkeepTobeExcel(@Valid UpkeepTobePageReqVO pageReqVO,
                                      HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<UpkeepTobeDO> list = upkeepTobeService.getUpkeepTobePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "待保养模具.xls", "数据", UpkeepTobeRespVO.class,
                BeanUtils.toBean(list, UpkeepTobeRespVO.class));
    }

    @PutMapping("/dispatch")
    @Operation(summary = "派工接口")
    @TransMethodResult
    public CommonResult<Boolean> dispatch(@Valid @RequestBody UpkeepTobeDispatchVO dispatchVO) {
        return success(upkeepTobeService.dispatch(dispatchVO));
    }

    @PutMapping("/cancel-dispatch")
    @Operation(summary = "撤销派工接口")
    @TransMethodResult
    public CommonResult<Boolean> cancelDispatch(@RequestParam("id") Long id) {
        try {
            return success(upkeepTobeService.cancelDispatch(id));
        } catch (ServiceException e) {
            return CommonResult.error(e.getCode(), e.getMessage());
        }
    }

    @PutMapping("/audit")
    @Operation(summary = "审核接口")
    @TransMethodResult
    public CommonResult<Boolean> audit(@Valid @RequestBody UpkeepTobeAuditVO auditVO) {
        try {
            return success(upkeepTobeService.audit(auditVO));
        } catch (ServiceException e) {
            return CommonResult.error(e.getCode(), e.getMessage());
        }
    }
}